IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fncGetAge]') 
											AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[fncGetAge]

GO

CREATE Function [dbo].[fncGetAge]
(
    @Birthday varchar(10),
    @Now smalldatetime
)
RETURNS INT
AS
BEGIN
    DECLARE @Birth smalldatetime
    DECLARE @Ret varchar(10)
	IF ((RTRIM(@Birthday)='')OR(@Birthday= NULL))
		BEGIN
			RETURN NULL
		END

	IF (LEN(@Birthday) = 8 )
	BEGIN
		SET @Birthday = LEFT(@Birthday,4) + '-' + RIGHT(LEFT(@Birthday,6),2)+ '-' + RIGHT(@Birthday,2)
	END 

    SET @Birth = CAST(@Birthday AS smalldatetime)
	RETURN (SELECT CASE
		WHEN DATEADD(year, DATEDIFF(year, @Birth, @Now), @Birth) > @Now
			THEN DATEDIFF(year, @Birth, @Now) - 1
		ELSE DATEDIFF(year, @Birth, @Now)
	END AS Age)
END



